package com.rongke.web.shiro;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.rongke.mapper.UserMapper;
import com.rongke.model.User;
import com.rongke.service.UserService;
import com.rongke.utils.Md5;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

@Transactional
public class PasswordRealm extends AuthorizingRealm {
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private UserService userService;

	/**
	 * 为当前登录的用户授予权限
	 */
	@Override
	public AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// // String phone = (String)principals.getPrimaryPrincipal();
		// SimpleAuthorizationInfo authorizationInfo = new
		// SimpleAuthorizationInfo();
		// try {
		//
		// } catch (Exception e) {
		// e.printStackTrace();
		// }
		// return authorizationInfo;
		return new SimpleAuthorizationInfo();
	}

	/**
	 * 验证当前登录的用户
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		String phone = (String) token.getPrincipal();
		// 用户名
		EntityWrapper<User> ew = new EntityWrapper<>();
		ew.eq("phone", phone);
		User user = userService.selectOne(ew);
		if (user != null) {
			AuthenticationInfo authcInfo = new SimpleAuthenticationInfo(phone,
					Md5.md5Encode("123"), getName());
			return authcInfo;
		} else {
			return null;
		}
	}
}
